package com.rimi.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rimi.bean.MenuBean;
import com.rimi.bean.RoleBean;
import com.rimi.service.MenuService;
import com.rimi.service.RoleService;

@Controller
public class RoleController {

	@Autowired
	private RoleService rs;
	@Autowired
	private MenuService ms;

	@RequestMapping("roleInfo")
	public String roleInfo(Model m) {
		m.addAttribute("list", rs.getRoleInfo());
		return "Role/index";
	}

	@RequestMapping("editRole")
	public String editRole(Model m, String isok, String name) {
		// 从页面内得到选中的菜单对象id
		List<Integer> list1 = rs.getMenuByRoleId(Integer.parseInt(isok));
		// 得到所有菜单对象
		List<MenuBean> list2 = ms.getMenuInfo();
		for (int i = 0; i < list2.size(); i++) {
			// 建立标识flag
			boolean flag = true;
			for (int j = 0; j < list1.size(); j++) {
				if (list1.get(j) == list2.get(i).getMenuId()) {
					list2.get(i).setMenuState(1);
					// 开关控制,这里输出了,下面就不输出,这里不输出下面就输出
					flag = false;
				}
			}
			if (flag) {
				list2.get(i).setMenuState(0);
			}
		}
		m.addAttribute("isok", isok);
		m.addAttribute("name", name);
		m.addAttribute("list2", list2);
		return "Role/editRole";
	}

	@RequestMapping("change")
	public String change(Model m, Integer[] group, Integer isok) {
		ms.change(isok);
		Map map = null;
		for (int i = 0; i < group.length; i++) {
			map = new HashMap();
			map.put("menu", ms.getMenuByMenuId(group[i]));

			map.put("role", rs.getRoleById(isok));
			ms.change2(map);
		}
		return "redirect:index.jsp";
	}

	@RequestMapping("delRole")
	public String delRole(Integer isok) {
		rs.delRole(isok);
		ms.delRole(isok);
		return "redirect:index.jsp";
	}

	@RequestMapping("addRole")
	public String addRole(Model m) {
		// 得到所有菜单对象
		List<MenuBean> list = ms.getMenuInfo();
		m.addAttribute("list", list);
		return "Role/addRole";
	}

	@RequestMapping("addIn")
	public String addIn(Model m, RoleBean mm, Integer[] group) {
		rs.addIn(mm);
		RoleBean rb = rs.selectRoleId(mm);
		Integer in = rb.getRoleId();
		Map map = null;
		for (int i = 0; i < group.length; i++) {
			map=new HashMap();
			map.put("menu", ms.getMenuByMenuId(group[i]));
			map.put("role", rs.getRoleById(in));
			
			ms.change2(map);
		}
		return "redirect:index.jsp";
	}

}
